package main;

import java.util.ArrayList;
import java.util.Collections;

import problemSpace.*;
import xml.*;

public class InitialSolution {

	/**
	 * Test van initiele oplossing
	 */
	public static void main(String[] args) {
		ConcretePlanning cp1 = createInitial();
		cp1.output.resultList.get(0).score = Evaluation.calcScore(cp1, true);
		Marshalling.marshall(cp1);
	}

	/**
	 * Create multiple solutions using random and select the best one
	 * @return Best random created initial solution
	 */
	public static ConcretePlanning createInitial() {
		long startTime = System.currentTimeMillis(); 
		// in ms
		long runTime = 5000;
		int runs = 0;
		String file = "planning2010-12-06-update.xml";
		ConcretePlanning cp = Marshalling.unmarshal(file);
		System.out.println("File read: " + cp.orders.size() + " orders, "+ cp.vehicles.size() + " vehicles, " + cp.stations.size()+ " stations");
		while (System.currentTimeMillis() < startTime + runTime || runs < 3) {
			// TODO niet uit de methode springen indien nog geen feasible oplossing gevonden is, the methoden rescheduleWorst hebben moeite om deze hard constraint te fixen aangezien deze niet bij orderCost wordt berekend (vermoed ik)
			for(Station s : cp.stations) s.occupied.clear();
			for(Vehicle v : cp.vehicles) v.occupied.clear();
			// DONTFIX: vehicles mogen niet van een station naar een ander 'springen'
			for (Order o : cp.orders) o.setRemainingVolume();

			if (cp.output.resultList == null) cp.output.resultList = new ArrayList<Result>();
			cp.output.resultList.add(new Result());
			cp.output.resultList.get(cp.output.resultList.size() - 1).deliveries = new ArrayList<Delivery>();

			// orders eens door elkaar schudden om random te zijn
			Collections.shuffle(cp.orders);

			HelperFunctions.rescheduleOrders(cp);

			// uitschrijven
			cp.output.resultList.get(cp.output.resultList.size() - 1).score = Evaluation.calcScore(cp, false);
			System.out.println("Initial solution "+runs+" generated: SCORE = "+ cp.output.resultList.get(cp.output.resultList.size() - 1).score);

			// eerste output is altijd de beste
			if (cp.output.resultList.size() > 1) {
				if (cp.output.resultList.get(1).score > cp.output.resultList.get(0).score) {
					// oude is nog de beste
					cp.output.resultList.remove(1);
				} else {
					// nieuwe betere
					cp.output.resultList.remove(0);
				}
			} 
			runs++;
		}
		return cp;
	}

}